package com.yogee.topseller.activity.my;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.NetUtil;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.login.model.bean.CheckBean;
import com.yogee.topseller.activity.login.model.bean.SMSbean;
import com.yogee.topseller.bean.UpdatePhoneBean;
import com.yogee.topseller.http.Config;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ModifyPhoneActivity extends HttpActivity {

    @BindView(R.id.phone_et)
    EditText phoneEt;
    @BindView(R.id.phone_getcode_tv)
    TextView codeTv;
    @BindView(R.id.phone_code_et)
    EditText phoneCodeEt;
    private int randomCode;
    private int cutdown = 60;
    private String phone = "";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    codeTv.setClickable(false);
                    codeTv.setText("已发送" + "(" + String.valueOf(cutdown) + ")");
//                    codeTv.setBackgroundDrawable(getResources().getDrawable(R.drawable.corens_100_gary));
//                    codeTv.setTextColor(Color.parseColor("#ffffff"));
                    cutdown--;
                    if (cutdown <= 60 && cutdown > 0) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                handler.sendEmptyMessage(0);
                            }
                        }, 1000);
                    } else {
                        handler.sendEmptyMessage(1);
                    }
                    break;
                case 1:
                    codeTv.setClickable(true);
                    codeTv.setText("发送验证码");
//                    codeTv.setBackgroundDrawable(getResources().getDrawable(R.drawable.corens_3_style));
//                    codeTv.setTextColor(getResources().getColor(R.color.colorStyle));
                    break;
            }

        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_modify_phone;
    }

    @Override
    protected void initView() {

    }

    @OnClick({R.id.modify_phone_back_iv, R.id.modify_phone_save_tv, R.id.phone_delete_iv, R.id.phone_getcode_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.modify_phone_back_iv:
                finish();
                break;
            case R.id.modify_phone_save_tv:
                String newPhone = phoneEt.getText().toString();
                if(TextUtils.isEmpty(newPhone)){
                    ToastUtils.showToast(this, "请输入手机号");
                    break;
                }else{
                    if(!AppUtil.validatePhone(newPhone)){
                        ToastUtils.showToast(this, "手机号不合法");
                        break;
                    }
                }
                String code = phoneCodeEt.getText().toString();
                if(TextUtils.isEmpty(code)){
                    ToastUtils.showToast(this, "请输入验证码");
                    break;
                }else{
                    if (code.equals(String.valueOf(randomCode))) {
                        updatePhone(AppUtil.getUserId(this), newPhone);
                    } else {
                        ToastUtils.showToast(this, "请检查验证码是否输入正确");
                    }
                }

                break;
            case R.id.phone_delete_iv:
                phoneEt.setText(null);
                break;
            case R.id.phone_getcode_tv:
                phone = phoneEt.getText().toString();
                randomCode = AppUtil.getRandomNumber(6);
                if (!phone.isEmpty()) {
                    if (AppUtil.validatePhone(phone))  {
                        userCheck(phone);
                    } else {
                        ToastUtils.showToast(this, "手机号格式不正确");
                    }
                } else {
                    ToastUtils.showToast(this, "手机号不能为空");
                }
                break;
        }
    }

    private void sendSms(final String phoneNum, final int random) {
        handler.sendEmptyMessage(0);
        if (!NetUtil.isNetworkAvailable()) {
            ToastUtils.showToast(this, "网络中断了，请重新链接网络。");
            return;
        }
        if (!TextUtils.isEmpty(phoneNum)) {
            new Thread() {
                public void run() {
                    try {
                        //准备获取短信验证码需要的基本信息
                        String result = null;
                        String url = "http://v.juhe.cn/sms/send";//请求接口地址
                        Map params = new HashMap();//请求参数
                        params.put("mobile", phoneNum);//接收短信的手机号码
                        params.put("tpl_id", Config.TPL_ID);//短信模板ID，请参考个人中心短信模板设置
                        params.put("tpl_value", Config.TPL_VALUE + random);//变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
                        params.put("key", Config.APPKEY);//应用APPKEY(应用详细页查询)
                        params.put("dtype", "");//返回数据的格式,xml或json，默认json
                        try {
                            result = net(url, params, "GET");
                            Gson gson = new Gson();
                            final SMSbean returnBean = gson.fromJson(result, SMSbean.class);
                            //短信发送完成，更新UI操作
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    checkCode(returnBean);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }


    public static String net(String strUrl, Map params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", Config.USERAGENT);
            conn.setUseCaches(false);
            conn.setConnectTimeout(Config.DEF_CONN_TIMEOUT);
            conn.setReadTimeout(Config.DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {

                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, Config.DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    public static String urlencode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    private void checkCode(SMSbean smSbean) {
        if (Integer.parseInt(smSbean.getError_code()) == 0) {
            ToastUtils.showToast(this, "验证码已经发送");
        } else {
            ToastUtils.showToast(this, smSbean.getError_code() + ":" + smSbean.getReason());
        }
    }

    private void userCheck(final String phone) {
        HttpManager.getInstance().userCheck(phone).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<CheckBean>() {
            @Override
            public void onNext(CheckBean o) {
                sendSms(phone, randomCode);
            }
        }, this));
    }

    private void updatePhone(String userid, String phone) {
        HttpManager.getInstance().updatePhone(userid, phone).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<UpdatePhoneBean>() {
            @Override
            public void onNext(UpdatePhoneBean o) {
                finish();
            }
        }, this));
    }
}